<template>
  <x-dialog :title="title" :show.sync="visible" v-if="visible" :before-close="handleClose" width="60%">
    <el-form :model="params" :rules="rules" ref="params" class="demo-form-inline" label-position="top">
      <el-row :gutter="36">
        <el-col :span="12">
          <el-form-item :label="$t('system.announcement.title')" prop="noticeTitle">
            <el-input
              v-model="params.noticeTitle"
              :placeholder="$t('system.announcement.placeholderInputTitle')"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.announcement.type')" prop="noticeType">
            <x-select
              :placeholder="$t('system.announcement.placeholderSelectType')"
              v-model="params.noticeType"
              :options="dictOptions['upms_notice.notice_type']"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.announcement.data')" prop="noticeTime">
            <el-date-picker
              v-model="params.noticeTime"
              type="datetime"
              style="width: 100%"
              value-format="yyyy-MM-dd HH:mm:ss"
              :placeholder="$t('system.announcement.dataPlaceholder')"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <!-- 富文本选择器 -->
        <el-col :span="24">
          <el-form-item :label="$t('system.announcement.content')" prop="noticeContext">
            <!-- 此处待处理富文本插入图片带有token的问题 -->
            <x-editor v-model="params.noticeContext" :excludeMenuKeys="['uploadImage', 'uploadVideo']"></x-editor>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('system.announcement.state')" prop="state">
            <x-radio-group :list-data="dictOptions['system.state']" v-model="params.state"></x-radio-group>
          </el-form-item>
        </el-col>
        <!-- 文件上传 -->
        <el-col :span="24">
          <el-form-item :label="$t('system.announcement.files')" prop="files">
            <x-upload
              ref="fileUpload"
              :edit-flag="true"
              :limit="9"
              :fileSize="20"
              :old-file-list="params.files"
              :file-type="['jpg', 'jpeg', 'png', 'ppt', 'pptx', 'pdf', 'xls', 'xlsx']"
            >
            </x-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer">
      <el-button @click="handleClose"> {{ $t('common.cancel') }} </el-button>
      <el-button
        type="primary"
        @click="
          loading = true
          handleSubmit()
        "
        :loading="loading"
      >
        {{ $t('common.save') }}
      </el-button>
    </span>
  </x-dialog>
</template>
<script>
  import { cloneDeep, omit, throttle, vaildEditor } from '@package/utils'
  import { apiPutEditNotice, apiPostAddNotice, apiGetNotice } from '../api/announcement.js'
  import { EnumApiCode } from '../../../../../../globalEnum'

  export default {
    props: {
      dictOptions: {
        type: Object
      }
    },
    data() {
      return {
        visible: false,
        loading: false,
        title: this.$t('system.announcement.add'),
        params: {
          noticeTitle: '',
          noticeType: '',
          noticeContext: '',
          noticeTime: '',
          files: [],
          state: '1'
        },
        isParent: true,
        rules: {
          noticeTitle: [
            { required: true, message: this.$t('system.announcement.placeholderInputTitle'), trigger: 'blur' }
          ],
          noticeTime: [{ required: true, message: this.$t('system.announcement.placeholderdTimes'), trigger: 'blur' }],
          noticeContext: [
            { required: true, message: this.$t('system.announcement.placeholderInputContent'), trigger: 'blur' },
            { validator: this.validateEditorText, trigger: 'blur' }
          ],
          noticeType: [
            { required: true, message: this.$t('system.announcement.placeholderSelectType'), trigger: 'blur' }
          ],
          state: [{ required: true, message: this.$t('system.announcement.placeholderStateType'), trigger: 'blur' }]
        }
      }
    },
    methods: {
      handleOpen(info) {
        this.visible = true
        if (info?.id) {
          this.title = this.$t('common.edit')
          apiGetNotice(info.id).then(({ data }) => {
            this.params = Object.assign(this.params, cloneDeep(data))
            this.params.state += ''
          })
          return
        }
        this.title = this.$t('system.announcement.add')
      },
      handleSubmit: throttle(function () {
        this.loading = true
        this.$refs.params.validate(async (valid) => {
          if (valid) {
            const param = {
              ...this.params,
              files: this.$refs.fileUpload.fileList.map((v) => {
                return {
                  fileName: v.name || v.fileName,
                  filePath: v.filePath || v.response.data.filePath,
                  fileType: (v.name || v.fileName).slice((v.name || v.fileName).lastIndexOf('.') + 1),
                  remark: v.remark
                }
              })
            }
            try {
              const { code, msg } = this.params.id ? await apiPutEditNotice(param) : await apiPostAddNotice(param)
              this.loading = false
              if (code === EnumApiCode.Success) {
                this.$message.success(param.id ? this.$t('common.editSuccess') : this.$t('common.newSuccess'))
                this.handleClose()
                this.$emit('handleSuccess')
              } else {
                this.$message.error(msg)
              }
            } finally {
              this.loading = false
            }
          } else {
            this.loading = false
            return false
          }
        })
      }, 1000),
      handleClose() {
        this.$refs.params.resetFields()
        this.params = omit(this.params, 'id')
        this.params.files = []
        this.loading = false
        this.visible = false
      },
      validateEditorText(rule, value, callback) {
        if (value && value !== '' && vaildEditor(value)) {
          callback(new Error(this.$t('system.announcement.placeholderInputContent')))
        } else {
          callback()
        }
      }
    }
  }
</script>
